/*
 *  Copyright (C) 2011 felixtheripper <felixtheripper_AT_gmail.com>
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package org.myorg.ctm.etk.gui.swg.display.help;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
import java.util.logging.Logger;
import javax.help.CSH;
import javax.help.HelpBroker;
import javax.help.HelpSet;
import org.myorg.shr.gui.swg.util.logging.FileHandlerShr;
import org.myorg.ctm.etk.gui.swg.util.property.PrpNamingEtk;

/**
 *
 * @author felixtheripper
 *
 * email: felixtheripper_AT_gmail.com
 * ... please remove "_AT_" from the above string to get the right email address
 *
 */

public class EtkCSH extends CSH
{
    // ----
    // begin: instantiate logger for this class
    final static private Logger _LOGGER_ = Logger.getLogger(EtkCSH.class.getName());

    static
    {
        EtkCSH._LOGGER_.addHandler(FileHandlerShr.s_getInstance());
    }

    // end: instantiate logger for this class
    // ----

    // --------------
    // STATIC PRIVATE

    static private java.util.Vector<Component> _s_vecCmpSetID = new java.util.Vector<Component>();



    // -------------
    // STATIC PUBLIC

    // first checkNDump main helpset, then do job for additionals
    static public boolean s_checkAndDumpCmp2ID(HelpSet hst)
    {
    	String str = System.getProperty(PrpNamingEtk.STR_PRP_DEBUG);

    	if (str == null )
    		return true;

    	if (str.compareToIgnoreCase("true") != 0)
    		return true;

        if (EtkCSH._s_vecCmpSetID == null)
        {
            EtkCSH._LOGGER_.severe("nil EtkCSH._s_vecCmpSetID");
            return false;
        }


        boolean blnGotNoValidId = false;

        for (int i=0; i<EtkCSH._s_vecCmpSetID.size(); i++)
        {
            Component cmpCur = (Component) EtkCSH._s_vecCmpSetID.elementAt(i);

            if (cmpCur == null)
            {
                EtkCSH._LOGGER_.severe("nil cmpCur");
                return false;
            }

            String strIDCur = CSH.getHelpIDString(cmpCur);

            if (strIDCur == null)
            {
                EtkCSH._LOGGER_.severe("nil strIDCur");
                return false;
            }


            if (! hst.getCombinedMap().isValidID(strIDCur, hst))
            {
                blnGotNoValidId = true;
                EtkCSH._LOGGER_.warning("not isValidID strIDCur=" + strIDCur + ", ignoring");
                // continuing in order to get all invalid Ids
            }
        }


        if (blnGotNoValidId)
        {
            EtkCSH._LOGGER_.warning("Got at least one invalid ID");
            return false;
        }

        // check for additional integrated helps, ie g4g
        if (! EtkCSH._s_checkAndDumpCmp2ID())
        	return false;

        // ending
        return true;
    }

    static private boolean _s_checkAndDumpCmp2ID()
    {
    	if (EtkCSH._MAP_hbrToVecCmpSetId==null || EtkCSH._MAP_hbrToVecCmpSetId.isEmpty())
    		return true;

    	Set<HelpBroker> set= EtkCSH._MAP_hbrToVecCmpSetId.keySet();
        Iterator<HelpBroker> iter = set.iterator();

        boolean blnGotNoValidId = false;

        while (iter.hasNext())
        {
          //HelpBroker hbrCur = (HelpBroker) EtkCSH._MAP_hbrToVecCmpSetId.get(iter.next());
           HelpBroker hbrCur = (HelpBroker) iter.next();


                    Vector<Component> vecCur = EtkCSH._MAP_hbrToVecCmpSetId.get(hbrCur);

          if (vecCur == null)
          {
              EtkCSH._LOGGER_.warning("nil vecCur");
              return false;
          }

          HelpSet hstCur = hbrCur.getHelpSet();

          if (hstCur == null)
          {
              EtkCSH._LOGGER_.severe("nil hstCur");
              return false;
          }

          for (int i=0; i<vecCur.size(); i++)
          {
              Component cmpCur = (Component) vecCur.elementAt(i);

              if (cmpCur == null)
              {
                  EtkCSH._LOGGER_.severe("nil cmpCur");
                  return false;
              }

              String strIDCur = CSH.getHelpIDString(cmpCur);

              if (strIDCur == null)
              {
                  EtkCSH._LOGGER_.severe("nil strIDCur");
                  return false;
              }

              if (! hstCur.getCombinedMap().isValidID(strIDCur, hstCur))
  	        {
              	blnGotNoValidId = true;
                EtkCSH._LOGGER_.warning("not isValidID strIDCur=" + strIDCur +", ignoring");
                  // continuing in order to get all invalid Ids
  	        }
          }

        }  // end of map iteration


        if (blnGotNoValidId)
        {
                EtkCSH._LOGGER_.severe("Got at least one invalid ID");
        	return false;
        }

    	return true;
    }


    static private HashMap<HelpBroker, Vector<Component>> _MAP_hbrToVecCmpSetId =
    	new HashMap<HelpBroker, Vector<Component>>();

    // specific helpbroker, ie geostats4geophy
    static public void setHelpIDString(Component cmpTarget, String strID, HelpBroker hbr)
    {
        if (cmpTarget == null)
        {
        	// TODO!
                EtkCSH._LOGGER_.severe("nil cmpTarget, exiting");
        	System.exit(1);
        }

        if (strID == null)
        {
        	//TODO!

                EtkCSH._LOGGER_.severe("nil strId, cmpTarget.getClass().toString()=" + cmpTarget.getClass().toString() + "\n exiting");
                System.exit(1);
        }

       Vector<Component> vecValue = EtkCSH._MAP_hbrToVecCmpSetId.get(hbr);

       if (vecValue == null)
       {
    	   vecValue = new Vector<Component>();
       	   EtkCSH._MAP_hbrToVecCmpSetId.put(hbr, vecValue);
       }

       vecValue.addElement(cmpTarget);

        CSH.setHelpIDString(cmpTarget, strID);
    }


    /**
        overwrites superclass's method
    **/
    static public void setHelpIDString(Component cmpTarget, String strID)
    {
        if (cmpTarget == null)
        {
        	// TODO!
                EtkCSH._LOGGER_.severe("nil cmpTarget, exiting");
        	System.exit(1);
        }

        if (strID != null)
        {


            EtkCSH._s_vecCmpSetID.addElement(cmpTarget);

            CSH.setHelpIDString(cmpTarget, strID);
        }

        else
        {
//        	 TODO!
        	EtkCSH._LOGGER_.severe("nil strId, cmpTarget.getClass().toString()=" + cmpTarget.getClass().toString() + ", exiting");
                System.exit(1);
        }
    }


    // -----------------------------------------
    // BEGIN STATIC CLASS EtkDisplayHelpFromFocus

    static public class EtkDisplayHelpFromFocus implements ActionListener
    {
        String strClassSub = "EtkDisplayHelpFromFocus.";

        // ------
        // PUBLIC

        public EtkDisplayHelpFromFocus(HelpBroker hbr)
        {

            if (hbr == null)
            {
                //MySystem.s_printOutExit(this, strMethod, "nil hbr");
            }

            if (! (hbr instanceof EtkHelpBroker))
            {
                //MySystem.s_printOutExit(this, strMethod, "! (hbr instanceof EtkHelpBroker)");
            }

            this._mhb = (EtkHelpBroker) hbr;

            try
            {
                this._alr = new CSH.DisplayHelpFromFocus(hbr);
            }

            catch(NullPointerException excNullPointer)
            {
                excNullPointer.printStackTrace();
                //MySystem.s_printOutExit(this, strMethod, "excNullPointer caught");
            }

            //strMethod = null;
        }

        public void actionPerformed(ActionEvent evtAction)
        {

            if (this._alr == null)
            {
                //MySystem.s_printOutExit(this, strMethod, "nil this._alr");
            }

            this._alr.actionPerformed(evtAction);

            javax.swing.SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    //String strMethod2 = strMethod + "." + "run()";

                    if (_mhb == null)
                    {
                        //MySystem.s_printOutTrace(this, strMethod2, "nil _mhb, maybe destroying");
                        //strMethod2 = null;
                        return;
                    }

                    if (! _mhb.assignStyleSheet())
                    {
                        //MySystem.s_printOutTrace(this, strMethod2, "failed, maybe destroying");
                        //strMethod2 = null;
                        return;
                    }

                    //strMethod2 = null;
                }
            });
        }

        // -------
        // PRIVATE

        private ActionListener _alr = null;
        private EtkHelpBroker _mhb = null;
    }

    // ---------------------------------------
    // END STATIC CLASS EtkDisplayHelpFromFocus

    // ---------------------------------------------
    // BEGIN STATIC CLASS EtkDisplayHelpAfterTracking

    static public class EtkDisplayHelpAfterTracking implements ActionListener
    {
        String strClassSub = "EtkDisplayHelpAfterTracking.";

        // ------
        // PUBLIC

        public EtkDisplayHelpAfterTracking(HelpBroker hbr)
        {

            if (hbr == null)
            {
                //MySystem.s_printOutExit(this, strMethod, "nil hbr");
            }

            if (! (hbr instanceof EtkHelpBroker))
            {
                //MySystem.s_printOutExit(this, strMethod, "! (hbr instanceof EtkHelpBroker)");
            }

            this._mhb = (EtkHelpBroker) hbr;


            try
            {
                this._alr = new CSH.DisplayHelpAfterTracking(hbr);
            }

            catch(NullPointerException excNullPointer)
            {
                excNullPointer.printStackTrace();
                //MySystem.s_printOutExit(this, strMethod, "excNullPointer caught");
            }
        }

        public void actionPerformed(ActionEvent evtAction)
        {

            if (this._alr == null)
            {
                // TODO !!!!
                EtkCSH._LOGGER_.warning("nil this._alr, aborting");

                return;
            }

            // CANNOT CATCH EXCEPTION !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            try
            {
                this._alr.actionPerformed(evtAction);
            }

            catch(javax.help.BadIDException excBadID)
            {
                excBadID.printStackTrace();
                //MySystem.s_printOutError(".actionPerfomed(evtAction)",
                        //"got excBadID, excBadID.getID()=" + excBadID.getID());

                //String strBody = "Got javax.help.BadIDException";
                //strBody += "\n" + excBadID.getMessage();
                //TODO: activate
                // EtkOptionPane.s_showDialogError(null, strBody);
                return;
            }


            javax.swing.SwingUtilities.invokeLater(new Runnable()
	        {
	            public void run()
	            {
	                //String strMethod2 = strMethod + "." + "run()";

                    if (_mhb == null)
                    {
                 
                        // TODO !!!!
                        EtkCSH._LOGGER_.warning("nil this._mhb, aborting");
                        return;
                    }

                    if (! _mhb.assignStyleSheet())
                    {
                        // TODO !!!!

                        EtkCSH._LOGGER_.warning("failed, aborting");
                        return;
                    }
	            }
	        });
        }

        // -------
        // PRIVATE

        private ActionListener _alr = null;
        private EtkHelpBroker _mhb = null;
    }

    // -------------------------------------------
    // END STATIC CLASS EtkDisplayHelpAfterTracking



    // ------------------------------------------
    // BEGIN STATIC CLASS EtkDisplayHelpFromSource

    static public class EtkDisplayHelpFromSource implements ActionListener
    {

        // ------
        // PUBLIC

        public EtkDisplayHelpFromSource(HelpBroker hbr)
        {

            if (hbr == null)
            {
                EtkCSH._LOGGER_.warning("nil hbr, aborting");
            	return;

            }

            if (! (hbr instanceof EtkHelpBroker))
            {
                EtkCSH._LOGGER_.warning("! (hbr instanceof EtkHelpBroker, aborting");
            	return;
            }

            try
            {
                this._alr = new CSH.DisplayHelpFromSource(hbr);
            }

            catch(NullPointerException excNullPointer)
            {
                excNullPointer.printStackTrace();
                //MySystem.s_printOutExit(this, strMethod, "excNullPointer caught");
            }
        }

        public void actionPerformed(ActionEvent evtAction)
        {

            if (this._alr == null)
            {
                //MySystem.s_printOutExit(this, strMethod, "nil this._alr");
                // !!
                return;
            }

            this._alr.actionPerformed(evtAction);

            /*javax.swing.SwingUtilities.invokeLater(new Runnable()
	        {
	            public void run()
	            {
	                //String strMethod2 = strMethod + "." + "run()";

                    if (_mhb == null)
                    {
                        //MySystem.s_printOutExit(this, strMethod2, "nil _mhb");
                    }

                    if (! _mhb.assignStyleSheet())
                    {
		                //MySystem.s_printOutExit(this, strMethod2, "failed");
                    }
	            }
	        });*/
        }

        // -------
        // PRIVATE

        private ActionListener _alr = null;
    }

    // ----------------------------------------
    // END STATIC CLASS EtkDisplayHelpFromSource
}
